#!/usr/bin/env python3
#! -*- coding: utf-8 -*-

import re
from typing import Dict, List, Tuple
import requests
import os

# Path or URL to rpm macros.in
# MACROS_IN_URL = 'https://raw.githubusercontent.com/rpm-software-management/rpm/master/macros.in'
# content = requests.get(MACROS_IN_URL).text.split('\n')
with open(os.path.join(os.path.dirname(__file__), 'macros.in'), 'r', encoding='utf-8') as f:
    content = f.read().splitlines()

in_arch_macro = False
result_lis: List[Tuple[str, List[str]]] = list()
name_maxlen = 0

exp = r'%(?P<name>\S+)\s*(?P<alias>.*)'
patt = re.compile(exp, re.I)

i = 0
for i in range(len(content)):
    line = content[i].strip()
    if line.startswith('# arch macro'):
        in_arch_macro = True
    if in_arch_macro and line.startswith('%'):
        res = re.match(patt, line)
        dic = res.groupdict()
        result_lis.append((dic.get('name'), dic.get('alias').split(' ')))
        name_maxlen = max(name_maxlen, len(dic.get('name')))
        if i + 1 < len(content) and not content[i + 1].startswith('%'):
            in_arch_macro = False

result_lis.sort(key=lambda x: x[0])
final_res = '| 宏名称 | `_arch` 宏对应值 |\n'
final_res += '| ------ | --------------- |\n'
for name, all_alias in result_lis:
    final_res += '| `%{}`{} | `{}` |\n'.format(
        name,
        ' ' * (name_maxlen - len(name)),
        '`, `'.join(all_alias)
    )
print(final_res)
